<template>
  <a-modal v-model:open="open" :title="formState.id ? '编辑班级': '新增班级'" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" style="margin-top: 16px">
      <a-form-item label="班级名" name="category_name" :rules="[{ required: true, message: '请输入班级名' }]">
        <a-input v-model:value="formState.category_name" placeholder="请输入班级名" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { fetchCategoryCreateOrUpdate } from '@/api/student'
import { message } from 'ant-design-vue'

const emits = defineEmits(['refresh'])

const open = ref(false)
const handleOk = () => {
  formRef.value.validate().then(async () => {
    const res = await fetchCategoryCreateOrUpdate(formState.value)
    if (res.data.code == '200') {
      message.success(`${formState.value.id ? '修改' : '新增'}成功`)
      emits('refresh')
      reset()
      open.value = false
    } else {
      message.error(res.data.message)
    }
  })
}
const handleCancel = () => {
  reset()
  open.value = false
}
const reset = () => {
  Object.keys(formState.value).forEach(key => {
    formState.value[key] = undefined
  })
}
const openModal = (record: any) => {
  if (record) {
    Object.keys(formState.value).forEach(key => {
      formState.value[key] = record[key]
    })
  }
  open.value = true
}

const formRef = ref()
const formState = ref<any>({
  id: undefined,
  category_name: undefined
})

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
